package cn.stylefeng.guns.modular.wxuser.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.goodsEvaluate.entity.TaoGoodsEvaluate;
import cn.stylefeng.guns.modular.goodsEvaluate.model.params.TaoGoodsEvaluateParam;
import cn.stylefeng.guns.modular.goodsEvaluate.service.TaoGoodsEvaluateService;
import cn.stylefeng.guns.modular.order.model.params.TbOrderParam;
import cn.stylefeng.guns.modular.order.service.TbOrderService;
import cn.stylefeng.guns.modular.shi.entity.SRecommend;
import cn.stylefeng.guns.modular.shi.entity.SRecommendEvaluation;
import cn.stylefeng.guns.modular.shi.model.params.SRecommendEvaluationParam;
import cn.stylefeng.guns.modular.shi.model.params.SRecommendParam;
import cn.stylefeng.guns.modular.shi.service.SRecommendEvaluationService;
import cn.stylefeng.guns.modular.shi.service.SRecommendService;
import cn.stylefeng.guns.modular.weixin.api.PayUtils;
import cn.stylefeng.guns.modular.wxuser.entity.MultipleResult;
import cn.stylefeng.guns.modular.wxuser.entity.MultipleSelect;
import cn.stylefeng.guns.modular.wxuser.entity.TaoWxUser;
import cn.stylefeng.guns.modular.wxuser.model.params.TaoWxUserParam;
import cn.stylefeng.guns.modular.wxuser.service.MultipleService;
import cn.stylefeng.guns.modular.wxuser.service.TaoWxUserService;
import cn.stylefeng.guns.sys.modular.tao.entity.Goods;
import cn.stylefeng.guns.sys.modular.tao.entity.GoodsPic;
import cn.stylefeng.guns.sys.modular.tao.service.GoodsPicService;
import cn.stylefeng.guns.sys.modular.tao.service.GoodsService;
import cn.stylefeng.guns.sys.modular.tao.shiUtil.ResponseMsg;
import cn.stylefeng.guns.sys.modular.tao.shiUtil.UploadFileUtils;
import cn.stylefeng.guns.sys.modular.tao.shiUtil.UploadResult;
import cn.stylefeng.guns.transfer.CertHttpUtil;
import cn.stylefeng.guns.transfer.CreateRandomUtil;
import cn.stylefeng.guns.transfer.WXPayConstant;
import cn.stylefeng.guns.transfer.XMLUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.*;


/**
 * 会员推广以及佣金
 */
@Controller
@RequestMapping("/taoWxUser")
@CrossOrigin("*")
public class TaoWxUserController extends BaseController {


    private static final String SystemConstant = "https://hybn-1259399233.cos.ap-chengdu.myqcloud.com/";

    /**
     * 图文 URL
     */
    public String pictureURL = "";

    /**
     * 视频 URL
     */
    public String videoURL = "";


    private final String APPID = "wxe09464398e58d00c";

    private final String SECRET = "e323345463f0203bdcb295e31190c004";

    private String url = "https://api.weixin.qq.com/cgi-bin/";


    private String PREFIX = "/taoWxUser";


    /**
     * 微信用户表
     */
    @Autowired
    private TaoWxUserService taoWxUserService;


    /**
     * 商品评价
     */
    @Autowired
    private TaoGoodsEvaluateService taoGoodsEvaluateService;


    /**
     * 商品表
     */
    @Autowired
    private GoodsService goodsService;


    /**
     * 商品种草表
     */
    @Autowired
    private SRecommendService sRecommendService;


    /**
     * 商品种草评价表
     */
    @Autowired
    private SRecommendEvaluationService sRecommendEvaluationService;


    /**
     * 商品图片表
     */
    @Autowired
    private GoodsPicService goodsPicService;


    /**
     * 商品订单表
     */
    private TbOrderService tbOrderService;


    /**
     * 使用查询模板
     */
    @Autowired
    private MultipleService multipleService;



    /**
     * 跳转到主页面
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/taoWxUser.html";
    }

    /**
     * 新增页面
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/taoWxUser_add.html";
    }

    /**
     * 编辑页面
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/taoWxUser_edit.html";
    }

    /**
     * 新增接口
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TaoWxUserParam taoWxUserParam) {
        this.taoWxUserService.add(taoWxUserParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(TaoWxUserParam taoWxUserParam) {
        this.taoWxUserService.update(taoWxUserParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(TaoWxUserParam taoWxUserParam) {
        this.taoWxUserService.delete(taoWxUserParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(TaoWxUserParam taoWxUserParam) {
        TaoWxUser detail = this.taoWxUserService.getById(taoWxUserParam.getId());
        if(detail.getMemberGrade().equals("0")){
            detail.setMemberGrade("普通用户");
        }else if(detail.getMemberGrade().equals("1")){
            detail.setMemberGrade("一级会员");
        }else if(detail.getMemberGrade().equals("2")){
            detail.setMemberGrade("二级会员");
        }else if(detail.getMemberGrade().equals("3")){
            detail.setMemberGrade("三级会员");
        }else if(detail.getMemberGrade().equals("4")){
            detail.setMemberGrade("体验会员");
        }else if(detail.getMemberGrade().equals("5")){
            detail.setMemberGrade("B端会员");
        }else if(detail.getMemberGrade().equals("6")){
            detail.setMemberGrade("授权会员");
        }
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author lcw
     * @Date 2019-10-22
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(TaoWxUserParam taoWxUserParam) {
        return this.taoWxUserService.findPageBySpec(taoWxUserParam);
    }




    /**
     * 通过openid查询用户详情
     */
    @RequestMapping(value = {"/getOpendId"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData getOpendId(TaoWxUser taoWxUser) {
        return ResponseData.success(taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getOpenId, taoWxUser.getOpenId())));
    }



    /**
     * 通过openid 修改佣金对应的值
     */
    @RequestMapping(value = {"/updateCommission"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData updateCommission(TaoWxUser taoWxUser, TaoWxUserParam taoWxUserParam) {
        TaoWxUser user = taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getOpenId, taoWxUser.getOpenId()));
        //查询原有金额
        BigDecimal credit = new BigDecimal(user.getCommissions().toString());
        //获取前端金额
        BigDecimal credits = new BigDecimal(taoWxUser.getCommissions().toString());
        //计算总金额
        BigDecimal addcredits = credits.add(credit);
        taoWxUserParam.setCommissions(addcredits);
        taoWxUserParam.setId(user.getId());
        taoWxUserService.update(taoWxUserParam);

        try {
            return ResponseData.success(200,"查询成功！",taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getOpenId,taoWxUser.getOpenId())));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.success(202,"接口异常！",0);
        }
    }



    /**
     * 微信提现
     */
    @RequestMapping(value = {"/transfer"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData transfer(String openid, String amount) {

        /** ==================================================封装提现所需参数================================================*/

        Map<String, String> restmap = null;
        String nonce_str = PayUtils.getRandomStringByLength(32);
        String danhao = String.valueOf(System.currentTimeMillis());
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("mch_appid", APPID); //公众账号appid
            parm.put("mchid", "1553191741"); //商户号
            parm.put("nonce_str", nonce_str); //随机字符串
            parm.put("partner_trade_no", danhao); //商户订单号
            parm.put("openid", openid); //用户openid oCVr20N2YLH9VQztnkZTaCj2aYYY
            parm.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
            //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
            parm.put("amount",amount); //转账金额
            //parm.put("desc", desc); //企业付款描述信息
            //parm.put("spbill_create_ip", IpAddrUtil.getIpAddr(request)); //Ip地址
            //parm.put("sign", PayUtil.getSign(parm, API_SECRET));

            //String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
            //restmap = XmlUtil.xmlParse(restxml);
        } catch (Exception e) {
            //logger.error(e.getMessage(), e);
            return null;
        }

        if (ToolUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
            System.out.println("转账成功");
            Map<String, String> transferMap = new HashMap<>();
            transferMap.put("partnerTradeNo", restmap.get("partner_trade_no"));//商户转账订单号
            transferMap.put("paymentNo", restmap.get("payment_no")); //微信订单号
            transferMap.put("paymentTime", restmap.get("payment_time")); //微信支付成功时间

            //生成流水表
            /*String waterId = UUID.randomUUID().toString().replaceAll("-", "");
            Map<String,Object> map = new HashMap<>();
            map.put("id",waterId);//编号
            //map.put("userId",userId);//用户id
            map.put("title","提现");//该流水的标题
            map.put("waterType",2);//商家流水类型1.场地收入 2.提现    用户流水类型1.分销收入 2.提现 3.预订场地
            map.put("incomeExpense",1);//收入还是支出 0.收入 1.支出
            map.put("applyMoney",applyMoney);//申请提现金额
            map.put("poundage",poundage);//手续费
            map.put("actualMoney",actualMoney);//实际金额
            map.put("whetherToAccount",1);//是否到账0.未到账1.已到账*/

            return ResponseData.success(transferMap);
        }
        return ResponseData.success();
    }





    /**
     * 微信提现备用接口
     */
    @RequestMapping(value = {"/transfers"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData transfers(String openid, String amount) {

        String key = WXPayConstant.PAY_APP_SECRET;

        // 1.0 拼凑企业支付需要的参数
        String appid = WXPayConstant.APP_ID; // 微信公众号的appid
        String mch_id = WXPayConstant.MCH_ID; // 商户号
        //String nonce_str = CreateRandomUtil.getRandom(20);// 随机字符串
        String nonce_str =CreateRandomUtil.getRandom(20);// 随机字符串
        String partner_trade_no="";
        String danhao = String.valueOf(System.currentTimeMillis());
        synchronized (this) {
            partner_trade_no = danhao;// 商户订单号
        }
        //String openid = appendid; // 支付给用户openid
        String check_name = "NO_CHECK"; // 是否验证真实姓名呢
        String re_user_name = "KOLO"; // 收款用户姓名(非必须)

        BigDecimal tmoney=new BigDecimal("100");
        BigDecimal newtmoney=new BigDecimal(amount);
        amount=newtmoney.multiply(tmoney).toString();

        Integer aaaaaaa= newtmoney.multiply(tmoney).intValue();
        String amounts = aaaaaaa.toString(); // 企业付款金额，最少为100，单位为分

        String desc = "恭喜你，提现成功"; // 企业付款操作说明信息。必填。
        String spbill_create_ip = "bgigclub.com"; // 用户的ip地址
        // 2.0 生成map集合
        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        //Map<String, String> packageParams = new HashMap<String, String>();
        packageParams.put("mch_appid", appid); // 微信公众号的appid
        packageParams.put("mchid", mch_id); // 商务号
        packageParams.put("nonce_str", nonce_str); // 随机生成后数字，保证安全性
        packageParams.put("partner_trade_no", partner_trade_no); // 生成商户订单号
        packageParams.put("openid", openid); // 支付给用户openid
        packageParams.put("check_name", check_name); // 是否验证真实姓名呢
        packageParams.put("re_user_name", re_user_name);// 收款用户姓名
        packageParams.put("amount", amounts); // 企业付款金额，单位为分
        packageParams.put("desc", desc); // 企业付款操作说明信息。必填。
        packageParams.put("spbill_create_ip", spbill_create_ip); // 调用接口的机器Ip地址

        try {
            //3.0 签名
            String sign = XMLUtil.createSign("UTF-8", packageParams,key);  //获取签名
            packageParams.put("sign", sign);
            // 5.0将当前的map结合转化成xml格式
            //String xml = WXPayUtil.mapToXml(packageParams);
            String xml = XMLUtil.getRequestXml(packageParams);//将请求参数转换成xml类型
            //String xml = MessageUtil.messageToXML(packageParams);// 打包要发送的xml
            // 6.0获取需要发送的url地址
            String wxUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 获取退款的api接口
            System.out.println("发送前的xml为：" + xml);
            // 7,向微信发送请求转账请求
            String returnXml = CertHttpUtil.postData(wxUrl, xml, WXPayConstant.MCH_ID, WXPayConstant.CLIENT_CERT_NAME);
            System.out.println("返回的returnXml为:" + returnXml);
            // 8，将微信返回的xml结果转成map格式
            Map returnMap = XMLUtil.doXMLParse(returnXml);


            if (returnMap.get("return_code").equals("SUCCESS")&&returnMap.get("return_msg").equals("")) {
                //写你要处理的逻辑,一般是操作数据库，写公司的业务逻辑
                return ResponseData.success();

            }
            return null;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }




    /**
     * 通过用户推广码获取 OpendId
     */
    @RequestMapping(value = {"/registrationGetOpendId"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData registrationGetOpendId(TaoWxUser taoWxUser) {
        return ResponseData.success(taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getGeneralizationCode, taoWxUser.getGeneralizationCode())));
    }





    /**
     * 上传图文 小程序和公众号
     */
    @RequestMapping(method = RequestMethod.POST, path = "/Apipicture")
    @ResponseBody
    public ResponseData Apipicture(@RequestPart("file") MultipartFile file, HttpSession session) throws FileNotFoundException {

        if (ToolUtil.isEmpty(file)){
            return  ResponseData.error(201,"上传失败，图片为空");
        }else{
            ResponseMsg msg = UploadFileUtils.uploadFile(file);
            if (msg.getStatus() == 10001){
                UploadResult result = (UploadResult) msg.getResult();
                pictureURL+=SystemConstant+result.getPath()+",";
                System.out.println("上传成功返回的地址："+pictureURL);
                return  ResponseData.success(200,"上传成功",SystemConstant+result.getPath()+",");
            }else {
                return  ResponseData.error(202,"上传失败，图片格式错误");
            }
        }
    }




    /**
     * 上传视频 小程序和公众号
     */
    @RequestMapping(method = RequestMethod.POST, path = "/Apivideo")
    @ResponseBody
    public ResponseData Apivideo(@RequestPart("file") MultipartFile file, HttpSession session) throws FileNotFoundException {

        if (ToolUtil.isEmpty(file)){
            return  ResponseData.error(201,"上传失败，视频为空");
        }else{
            ResponseMsg msg = UploadFileUtils.uploadFile(file);
            if (msg.getStatus() == 10001){
                UploadResult result = (UploadResult) msg.getResult();
                videoURL+=SystemConstant+result.getPath()+",";
                System.out.println("上传成功返回的地址："+SystemConstant+result.getPath()+",");
                return  ResponseData.success(200,"上传成功",SystemConstant+result.getPath()+",");
            }else {
                return  ResponseData.error(202,"上传失败，视频格式错误");
            }
        }
    }




    /**
     * 保存用户的评价
     */
    @RequestMapping(value = {"/preservationEvaluation"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData preservationEvaluation(TaoGoodsEvaluateParam taoGoodsEvaluateParam) {
        taoGoodsEvaluateParam.setTime(new Date());
        taoGoodsEvaluateParam.setEvaluateStars(taoGoodsEvaluateParam.getEvaluateStars()+"星评价");
        taoGoodsEvaluateParam.setServiceAttitude(taoGoodsEvaluateParam.getServiceAttitude()+"星评价");
        taoGoodsEvaluateParam.setLogisticsService(taoGoodsEvaluateParam.getLogisticsService()+"星评价");
        this.taoGoodsEvaluateService.add(taoGoodsEvaluateParam);
        return ResponseData.success();
    }




    /**
     * 用户通过 商品ID 和oppendID 分页查询数据
     */
    @RequestMapping(value = "/goodsEvaluatePaging",method = RequestMethod.POST)
    @ResponseBody
    public Object goodsEvaluatePaging(HttpServletRequest request,TaoGoodsEvaluate GoodsEvaluate){
        IPage<TaoGoodsEvaluate> page = new Page<>(Integer.valueOf(request.getParameter("pageNo")), Integer.valueOf(request.getParameter("pageSize")));
        QueryWrapper<TaoGoodsEvaluate> wrapper = new QueryWrapper<>();
        if(ToolUtil.isEmpty(GoodsEvaluate.getWxOpenId())){
            wrapper.eq("good_id",GoodsEvaluate.getGoodId() == null ?"" : GoodsEvaluate.getGoodId()).orderByDesc("time");
        }else if(ToolUtil.isEmpty(GoodsEvaluate.getGoodId())){
            wrapper.eq("wx_open_id",GoodsEvaluate.getWxOpenId() == null ? "" : GoodsEvaluate.getWxOpenId()).orderByDesc("time");
        }
        if(ToolUtil.isEmpty(wrapper)){
            return ResponseData.error(202,"请求失败！",0);
        }else{
            IPage<TaoGoodsEvaluate> pages = taoGoodsEvaluateService.page(page,wrapper);
            for(TaoGoodsEvaluate row:pages.getRecords()){
                try {
                    if(ToolUtil.isEmpty(GoodsEvaluate.getGoodId())){
                        QueryWrapper<TaoWxUser> QueryWrapperList = new QueryWrapper<>();
                        QueryWrapperList.eq("open_id",row.getWxOpenId());
                        List<TaoWxUser> TaoWxUserList = taoWxUserService.list(QueryWrapperList);
                        row.setWeixinName(TaoWxUserList.get(0).getNickName());
                        row.setGoodNames(goodsService.getById(row.getGoodId()).getFullname());
                        row.setWxHeadImageUrl(TaoWxUserList.get(0).getHeadImageUrl());
                    }else{
                        System.out.println();
                        QueryWrapper<TaoWxUser> QueryWrapperList = new QueryWrapper<>();
                        QueryWrapperList.eq("open_id",row.getWxOpenId());
                        List<TaoWxUser> TaoWxUserList = taoWxUserService.list(QueryWrapperList);
                        row.setWeixinName(TaoWxUserList.get(0).getNickName());
                        row.setGoodNames(goodsService.getById(row.getGoodId()).getFullname());
                        row.setWxHeadImageUrl(TaoWxUserList.get(0).getHeadImageUrl());
                    }
                } catch (NullPointerException e) {
                    System.out.println("发生异常的原因为 :"+e.getMessage());
                }
            }
            return ResponseData.success(200,"请求成功！",pages);
        }
    }





    /**
     * 通过 openid 查询数据 商品种草表
     */
    @RequestMapping(value = "/QuerysRecommend",method = RequestMethod.POST)
    @ResponseBody
    public Object QuerysRecommend(HttpServletRequest request,SRecommend secommend){
        Long thumb;  //是否点赞标识

        IPage<SRecommend> page = new Page<>(Integer.valueOf(request.getParameter("pageNo")), Integer.valueOf(request.getParameter("pageSize")));
        QueryWrapper<SRecommend> wrapper = new QueryWrapper<>();
        if(ToolUtil.isEmpty(secommend.getOpenid())){
            wrapper.orderByDesc("adding_time");
        }else{
            wrapper.eq("openid",secommend.getOpenid()).orderByDesc("adding_time");
        }
        if(ToolUtil.isEmpty(wrapper)){
            return ResponseData.error(202,"请求失败！",0);
        }else{
            QueryWrapper<SRecommendEvaluation> w = new QueryWrapper<>();
            w.eq("openid",secommend.getOpenid());
            List<SRecommendEvaluation> list = sRecommendEvaluationService.list(w);
            if(list.size()>0){
                thumb = list.get(0).getLikeid();
                IPage<SRecommend> pages = sRecommendService.page(page,wrapper);
                for (SRecommend row:pages.getRecords()) {
                    row.setThumb(thumb);
                }
                return ResponseData.success(200,"请求成功！",pages.getRecords());
            }else{
                IPage<SRecommend> pages = sRecommendService.page(page,wrapper);
                return ResponseData.success(200,"请求成功！",pages.getRecords());
            }
        }
    }




    /**
     * 移动端发表 商品种草表
     */
    @RequestMapping(value = "/ApiSRecommend",method = RequestMethod.POST)
    @ResponseBody
    public Object ApiSRecommend(SRecommendParam sRecommendParam , TbOrderParam tbOrderParam){
        try {
                /**
                 * 修改种草状态
                 */
                tbOrderParam.setIsTree(1);
                tbOrderParam.setOrderId(tbOrderParam.getOrderId());
                tbOrderParam.setGoodsId(tbOrderParam.getGoodsId());
                int isTree = taoWxUserService.updateIsTree(tbOrderParam);
                if(isTree>0){
                    System.out.println("执行成功！");
                }else{
                    System.out.println("执行失败！");
                }
                Goods Goods = goodsService.getByIds(Long.parseLong(sRecommendParam.getNameId()));
                sRecommendParam.setNameId(Goods.getId().toString());
                sRecommendParam.setNames(Goods.getFullname());
                sRecommendParam.setAddingTime(new Date());
                GoodsPic pic = goodsPicService.getByGoodsId(String.valueOf(sRecommendParam.getId()));
                sRecommendParam.setPicturesUrl(sRecommendParam.getPicturesUrl());
                System.out.println();
                sRecommendParam.setOpenid(sRecommendParam.getOpenid());
                sRecommendParam.setDzTotal(Long.parseLong("0"));
                sRecommendParam.setEvaluationQuantity(Long.parseLong("0"));
                sRecommendParam.setContents(sRecommendParam.getContents());
                sRecommendParam.setThumb(Long.parseLong("0"));
                this.sRecommendService.add(sRecommendParam);
                return ResponseData.success(200,"种草成功！",0);

        } catch (NullPointerException e) {
            System.out.println("发生异常的原因为 :"+e.getMessage());
            return ResponseData.error(202,"种草失败！",1);
        }
    }






    /**
     * 修改种草状态
     */
    @RequestMapping(value = {"/updateIsTree"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData updateIsTree(TbOrderParam tbOrderParam) {
        try {
            tbOrderParam.setIsTree(1);
            tbOrderParam.setOrderId(tbOrderParam.getOrderId());
            tbOrderParam.setGoodsId(tbOrderParam.getGoodsId());
            int isTree = taoWxUserService.updateIsTree(tbOrderParam);
            if(isTree>0){
                System.out.println("执行成功！");
                return ResponseData.success(200,"执行成功！",1);
            }else{
                System.out.println("执行失败！");
                return ResponseData.error(202,"执行失败！",0);
            }
        } catch (Exception es) {
            es.printStackTrace();
            System.out.println("抛出异常"+es.getMessage());
            return ResponseData.error(202,"v！",0);
        }

    }






    /**
     * 移动端发表 商品种草评价表
     */
    @RequestMapping(value = "/ApisRecommendEvaluation",method = RequestMethod.POST)
    @ResponseBody
    public Object ApisRecommendEvaluation(SRecommendEvaluationParam sRecommendEvaluationParam, SRecommendParam sRecommendParam){
        boolean f = false;
        try {
            Goods Goods = goodsService.getByIds(Long.parseLong(sRecommendEvaluationParam.getNameId()));
            sRecommendEvaluationParam.setNameId(Goods.getId().toString());
            sRecommendEvaluationParam.setName(Goods.getFullname());
            sRecommendEvaluationParam.setEvaluationTime(new Date());
            sRecommendEvaluationParam.setContents(sRecommendEvaluationParam.getContents());
            sRecommendEvaluationParam.setOpenid(sRecommendEvaluationParam.getOpenid());
            sRecommendEvaluationParam.setOpenidName(taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getOpenId,sRecommendEvaluationParam.getOpenid())).getNickName());
            sRecommendEvaluationParam.setLikeid(Long.parseLong("0"));
            sRecommendEvaluationParam.setLikeidName("未点赞");
            sRecommendEvaluationService.add(sRecommendEvaluationParam);
            f = true;
        } catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("发生异常的原因为 :"+e.getMessage());
        }
        try {
            if(f == true){
                SRecommend secommend = sRecommendService.getOne(Wrappers.<SRecommend>lambdaQuery().eq(SRecommend::getNameId,sRecommendEvaluationParam.getNameId()));
                Long evaluationQuantity = secommend.getEvaluationQuantity()+1;
                sRecommendParam.setEvaluationQuantity(evaluationQuantity);
                sRecommendParam.setId(secommend.getId());
                sRecommendService.update(sRecommendParam);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("发生异常的原因为 :"+e.getMessage());
        }
        return ResponseData.success();
    }





    /**
     * 通过 openid 和商品id 查询数据 商品种草评价表
     */
    @RequestMapping(value = "/QuerySRecommendEvaluation",method = RequestMethod.POST)
    @ResponseBody
    public Object QuerySRecommendEvaluation(HttpServletRequest request,SRecommendEvaluation secommendEvaluation){

        IPage<SRecommendEvaluation> page = null;
        try {
            page = new Page<>(Integer.valueOf(request.getParameter("pageNo")), Integer.valueOf(request.getParameter("pageSize")));
            QueryWrapper<SRecommendEvaluation> wrapper = new QueryWrapper<>();
            if(ToolUtil.isEmpty(secommendEvaluation.getOpenid()) && ToolUtil.isEmpty(secommendEvaluation.getNameId())){
                wrapper.orderByDesc("evaluation_time");
            }else{
                wrapper.eq("name_id",secommendEvaluation.getNameId()).eq("openid",secommendEvaluation.getOpenid()).orderByDesc("evaluation_time");
            }
            if(ToolUtil.isEmpty(wrapper)){
                return ResponseData.error(202,"请求失败！",0);
            }else{
                IPage<SRecommendEvaluation> pages = sRecommendEvaluationService.page(page,wrapper);
                return ResponseData.success(200,"请求成功！",pages.getRecords());
            }
        } catch (NullPointerException e) {
            System.out.println("抛出异常！"+e.getMessage());
        }
        return ResponseData.success();
    }






    /**
     * 移动端 商品点赞功能
     */
    @RequestMapping(value = "/ApiGiveModeHttpFilters",method = RequestMethod.POST)
    @ResponseBody
    public Object ApiGiveModeHttpFilters(SRecommendEvaluationParam sRecommendEvaluationParam, SRecommendParam sRecommendParam){
        try {
            if(sRecommendEvaluationParam.getLikeid() == 0){
                /**
                 * 未点赞状态, 就改成已点赞
                 */
                QueryWrapper<SRecommendEvaluation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid",sRecommendEvaluationParam.getOpenid());
                List<SRecommendEvaluation> SRecommendEvaluationList = sRecommendEvaluationService.list(queryWrapper);
                for (int i = 0; i<SRecommendEvaluationList.size(); i++){
                    sRecommendEvaluationParam.setLikeid(Long.parseLong("1"));
                    sRecommendEvaluationParam.setLikeidName("已点赞");
                    sRecommendEvaluationParam.setId(SRecommendEvaluationList.get(i).getId());
                    sRecommendEvaluationService.update(sRecommendEvaluationParam);
                }
                try{
                    SRecommend secommend = sRecommendService.getOne(Wrappers.<SRecommend>lambdaQuery().eq(SRecommend::getNameId,sRecommendEvaluationParam.getNameId()));
                    Long dzTotal = secommend.getDzTotal();
                    sRecommendParam.setDzTotal(dzTotal+1);
                    sRecommendParam.setNameId(secommend.getNameId());
                    sRecommendParam.setId(secommend.getId());
                    sRecommendParam.setThumb(Long.parseLong("1"));
                    sRecommendService.update(sRecommendParam);
                    System.out.println("--------------------点赞成功！------------------");
                    return ResponseData.success(200,"点赞成功！",1);
                }catch (NullPointerException e) {
                    e.printStackTrace();
                    System.out.println("发生异常的原因为 :"+e.getMessage());
                }
            }else if(sRecommendEvaluationParam.getLikeid() == 1){
                /**
                 * 已点赞状态，就改成未点赞
                 */
                QueryWrapper<SRecommendEvaluation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid",sRecommendEvaluationParam.getOpenid());
                List<SRecommendEvaluation> SRecommendEvaluationList = sRecommendEvaluationService.list(queryWrapper);
                for (int i = 0; i<SRecommendEvaluationList.size(); i++){
                    sRecommendEvaluationParam.setLikeid(Long.parseLong("0"));
                    sRecommendEvaluationParam.setLikeidName("未点赞");
                    sRecommendEvaluationParam.setId(SRecommendEvaluationList.get(i).getId());
                    sRecommendEvaluationService.update(sRecommendEvaluationParam);
                    System.out.println();
                }
                try{
                    SRecommend secommend = sRecommendService.getOne(Wrappers.<SRecommend>lambdaQuery().eq(SRecommend::getNameId,sRecommendEvaluationParam.getNameId()));
                    Long dzTotal = secommend.getDzTotal();
                    if(dzTotal == 0){
                        System.out.println("--------------------取消点赞！------------------");
                        return ResponseData.success(200,"取消点赞！",0);
                    }else{
                        sRecommendParam.setDzTotal(dzTotal-1);
                        sRecommendParam.setNameId(secommend.getNameId());
                        sRecommendParam.setId(secommend.getId());
                        sRecommendParam.setThumb(Long.parseLong("0"));
                        sRecommendService.update(sRecommendParam);
                        System.out.println();
                        System.out.println("--------------------取消点赞！------------------");
                        return ResponseData.success(200,"取消点赞！",0);
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    System.out.println("发生异常的原因为 :"+e.getMessage());
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("发生异常的原因为 :"+e.getMessage());
        }
        System.out.println("--------------------未知错误，点赞失败！！------------------");
        return ResponseData.error(1225,"未知错误，点赞失败！",0);
    }





    /**
     * 根据用户推广码 generalizationCode
     * 查询 openIdQuerysRecommend
     */
    @RequestMapping(value = {"/generalizationCodeGetopenId"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData generalizationCodeGetopenId(TaoWxUser taoWxUser) {       //wrapper.eq("good_id",GoodsEvaluate.getGoodId() == null ?"" : GoodsEvaluate.getGoodId()).orderByDesc("time");
        try {
            return ResponseData.success(200,"查询成功！",taoWxUserService.getOne(Wrappers.<TaoWxUser>lambdaQuery().eq(TaoWxUser::getGeneralizationCode,taoWxUser.getGeneralizationCode() == null ? "" : taoWxUser.getGeneralizationCode())));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(202,"接口异常！",0);
        }
    }





    /**
     * 使用查询模板
     * 查询种草表，和种草评价表所有数据
     */
    @RequestMapping(value = {"/gatAllTable"},method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData gatAllTable( ) {
        try {
            MultipleSelect multipleSelect = MultipleSelect.newInstance("${1},${2}" ,new SRecommend(),new SRecommendEvaluation());
            multipleSelect.setPage(1,4);//setPage分页从1开始
            multipleService.mulSelect(multipleSelect);
            return ResponseData.success(200,"使用查询模板查询成功！",multipleService.mulSelect(multipleSelect));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error(202,"接口异常！",0);
        }
    }










}


